package com.cwf.auth.service.impl;

import com.cwf.auth.domain.Menu;
import com.cwf.auth.domain.Permission;
import com.cwf.auth.domain.Role;
import com.cwf.auth.dto.RoleMenuDTO;
import com.cwf.auth.dto.RolePermissionDTO;
import com.cwf.auth.mapper.MenuMapper;
import com.cwf.auth.mapper.RoleMapper;
import com.cwf.auth.service.IRoleService;
import com.cwf.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.sql.Array;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cwf
 * @since 2023-12-01
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
//    @Autowired
//    private MenuMapper menuMapper;

    @Transactional
    @Override
    public void saveAuth(RolePermissionDTO rolePermissionDTO) {
        // 判断表中是否有权限：1.通过角色id查询2.直接根据id清空角色权限，再重新赋值
        roleMapper.deletePermissionByRoleId(rolePermissionDTO);
        if (!rolePermissionDTO.getPermissions().isEmpty()){
            roleMapper.saveAuth(rolePermissionDTO);
        }
    }

    @Override
    public List<Long> getPermissionsById(Long id) {
        return roleMapper.getPermissionsById(id);
    }

    @Override
    public void saveMenu(RoleMenuDTO roleMenuDTO) {
        roleMapper.deleteMenuByRoleId(roleMenuDTO);
        if (!roleMenuDTO.getMenus().isEmpty()){
            /*List<Menu> ids = roleMenuDTO.getMenus();
            ArrayList<Long> list = new ArrayList<>();
            for (int i = 0; i < ids.size(); i++) {
                list.add(ids.get(i).getId());

            }
            for (int i = 0; i < list.size(); i++) {
                Menu menu = menuMapper.queryById(list.get(i));
                if (Objects.nonNull(menu.getParent())){
                    list.add(menu.getParent().getId());
                }
            }
            ArrayList<Long> menus = new ArrayList<>(new HashSet<>(list));
            roleMenuDTO.setIds(menus);*/
            roleMapper.saveMenu(roleMenuDTO);
        }
    }

    @Override
    public List<Long> getMenusById(Long id) {
        return roleMapper.getMenusById(id);
    }

    @Override
    public void delete(Serializable id) {
        // 根据角色id清空菜单和权限
        roleMapper.truncatePermissionsByRoleId(id);
        roleMapper.truncateMenusByRoleId(id);
        // 删除角色
        roleMapper.delete(id);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        // 根据角色ids清空菜单和权限
        roleMapper.truncatePermissionsByIds(ids);
        roleMapper.truncateMenusByIds(ids);
        // 删除角色
        roleMapper.batchDelete(ids);
    }
}
